#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt5.QtWidgets import QMainWindow,QApplication
from PyQt5.QtWidgets import QMessageBox,QListWidget,QListWidgetItem,QListView
from PyQt5.QtGui import QIcon

from forms.mainform import Ui_MainWindow
from toFuelRecordForm import ToFuelRecordForm
from maintenceRecordForm import MaintenceRecordForm
from settingForm import  SettingForm

import dbUtil

class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # Set up the user interface from Designer.
        self.setupUi(self)
        for i in range(0,self.swFaces.count()):
            self.swFaces.removeWidget(self.swFaces.widget(i))
        if not dbUtil.createConnection():
            QMessageBox.warning(self,"警告信息","数据库打开失败！")
        self.swFaces.insertWidget(0,ToFuelRecordForm())
        self.swFaces.insertWidget(1,MaintenceRecordForm())
        self.swFaces.insertWidget(2,SettingForm())
        self.lwFaces.setViewMode(QListView.IconMode)
        self.lwFaces.setFlow(QListView.TopToBottom)
        self.lwFaces.setSpacing(20)
        self.lwFaces.currentRowChanged.connect(self.swFaces.setCurrentIndex)
        QListWidgetItem(QIcon(":/icons/fuelRecord.png"),'加油',self.lwFaces)
        QListWidgetItem(QIcon(":/icons/maintence.png"),'维护',self.lwFaces)
        QListWidgetItem(QIcon(":/icons/settings.png"),'设置',self.lwFaces)
        self.lwFaces.setCurrentRow(0)
        self.actSetting.triggered.connect(self.onSettingSelected)
        self.actExit.triggered.connect(QApplication.instance().closeAllWindows)

    def closeEvent(self, event):
        if self.maybeSave():
            #QMessageBox.critical(self,'出错信息','保存出错！')
            event.accept()
        else:
            event.ignore()

    def maybeSave(self):
        self.swFaces.widget(0).submit()
        self.swFaces.widget(2).save()
        return True

    def onSettingSelected(self):
        self.lwFaces.setCurrentRow(2)
